/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

import ContentManagers.Models.Product;
import ContentManagers.RoleManagers.AdminManager;
import ContentManagers.RoleManagers.PMManager;
import ContentManagers.Security.Validator;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Ervin James
 */
public class ServletManageProduct extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            
            if(request.getParameter("SubmitManage").equals("Update"))
            {
                String name = Validator.inputSanitizer(request.getParameter("product_name"));
                String description= Validator.inputSanitizer(request.getParameter("description"));
                String sPrice = request.getParameter("price");
                session.setAttribute("formNo", request.getParameter("productIndex"));
                double fPrice;
               
                
                //validation part
                if(name.length()>45 || name.isEmpty()) {
                     //identify which form
                    WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product failed. Manager: " + session.getAttribute("username"),false);
                    session.setAttribute("errorMessage", "1");
                    response.sendRedirect("./Managing Interface/managing_index.jsp");
                }    

                else if(description.length()>500 || description.isEmpty()) {
                    WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product failed. Manager: " + session.getAttribute("username"),false);
                    session.setAttribute("errorMessage", "2");
                    response.sendRedirect("./Managing Interface/managing_index.jsp");
                }

                //ERROR HERE 
                else if(sPrice.isEmpty()||sPrice.length()>6)
                {
                    WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product failed. Manager: " + session.getAttribute("username"),false);
                    session.setAttribute("errorMessage", "3");
                    response.sendRedirect("./Managing Interface/managing_index.jsp");
                }

                else 
                {                
                    fPrice = Double.parseDouble(sPrice);
                 
                    if(fPrice <= 0 || fPrice>999999)
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product failed. Manager: " + session.getAttribute("username"),false);
                        session.setAttribute("errorMessage", "3");
                        response.sendRedirect("./Managing Interface/managing_index.jsp");
                    }
                    else 
                    {                       
                        boolean check=false;    
                        Product newProduct = new Product();
                        ArrayList indexer = (ArrayList)session.getAttribute("indexer");        
                        //get index from form
                        int getIndex = Integer.parseInt(request.getParameter("productIndex"));
                        //extract value from array
                        String stringProductID = indexer.get(getIndex).toString();
                        //convert to int
                        int productID = Integer.parseInt(stringProductID);

                        //set values for model
                        newProduct.setName(name);
                        newProduct.setDescription(description);
                        newProduct.setPrice(fPrice);
                        newProduct.setPid(productID);
                        
                        boolean exist = new PMManager().checkProduct2(newProduct);
                        if(exist==true)
                        {
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product failed. Product already exists. Manager: " + session.getAttribute("username"),false);
                            session.setAttribute("errorMessage", "6");
                            response.sendRedirect("./Managing Interface/managing_index.jsp");
                        }
                        else{
                            check = new PMManager().editProduct(newProduct);

                            if(check == true)
                            {
                                WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product successful. Manager: " + session.getAttribute("username"),true);
                                session.setAttribute("errorMessage", "4");
                                response.sendRedirect("./Managing Interface/managing_index.jsp");  
                            }
                            else
                            {
                                WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Edit product failed. Manager: " + session.getAttribute("username"),false);
                                session.setAttribute("errorMessage", "5");
                                response.sendRedirect("./Managing Interface/managing_index.jsp");
                            }
                        }
                    }
                }
            }
            else if(request.getParameter("SubmitManage").equals("Delete"))
            {
                boolean check =false;
                
                ArrayList indexer = (ArrayList)session.getAttribute("indexer");        

                //get index from form
                int getIndex = Integer.parseInt(request.getParameter("productIndex"));

                //extract value from array
                String stringProductID = indexer.get(getIndex).toString();

                //convert to int
                int productID = Integer.parseInt(stringProductID);
                
                Product p = new Product();
                p.setPid(productID);
                
                check = new PMManager().deleteProduct(p);
            
                if(check==true)
                {
                    response.sendRedirect("./Managing Interface/managing_index.jsp");
                }
                else
                {
                    //identify which form
                    session.setAttribute("formNo", request.getParameter("productIndex"));
                    //identify error message
                    session.setAttribute("errorMessage", "2");
                    response.sendRedirect("./Managing Interface/managing_index.jsp");
                }

                }
                else if(request.getParameter("SubmitManage").equals("Restore Item"))
                {
                    boolean check =false;
                
                    ArrayList indexer = (ArrayList)session.getAttribute("indexer");        

                    //get index from form
                    int getIndex = Integer.parseInt(request.getParameter("productIndex"));

                    //extract value from array
                    String stringProductID = indexer.get(getIndex).toString();

                    //convert to int
                    int productID = Integer.parseInt(stringProductID);

                    Product p = new Product();
                    p.setPid(productID);

                    check = new PMManager().restoreProduct(p);

                    if(check==true)
                    {
                        response.sendRedirect("./Managing Interface/managing_index.jsp");
                    }
                    else
                    {
                        //identify which form
                        session.setAttribute("formNo", request.getParameter("productIndex"));
                        //identify error message
                        session.setAttribute("errorMessage", "2");
                        response.sendRedirect("./Managing Interface/managing_index.jsp");
                    }
                    
                }
            } finally {            
                    out.close();
                }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
